package app.itgungnir.compose.wan.business.splash

import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import app.itgungnir.compose.wan.Routes
import app.itgungnir.compose.wan.theme.switchColorPalette
import app.itgungnir.compose.wan.theme.switchFontTypography
import app.itgungnir.compose.wan.utils.LocalDataStore

@Composable
fun SplashScreen(navController: NavController = rememberNavController()) {
    val viewModel = viewModel<SplashViewModel>()
    // UI
    SplashUI(LocalDataStore.localData.hasLaunched) {
        viewModel.jump()
    }
    // State observations
    JumpObservation(viewModel = viewModel, navController = navController)
}

@Composable
private fun JumpObservation(
    viewModel: SplashViewModel = viewModel(),
    navController: NavController = rememberNavController()
) {
    val jumpState by viewModel.jumpState.collectAsState()
    LaunchedEffect(key1 = jumpState) {
        jumpState?.let { data ->
            switchColorPalette(data.first)
            switchFontTypography(data.second)
            navController.navigate(Routes.MAIN) {
                popUpTo(Routes.SPLASH) { inclusive = true }
                launchSingleTop = true
            }
        }
    }
}
